<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/inframe
 * User: linzh
 * Date: 6/27/17
 * Time: 3:32 PM
 */


namespace inframe\library;

use Workerman\Worker;

/**
 * Class Service
 *
 *
 * workerman 使用@抑制错误的解决办法：
 * Workerman[service/vmstat.php] start in DEBUG mode
 * array(4) {
 *  ["message"]=>
 *      string(127) "file_get_contents(/home/mint/workspace/inframe/application/runtime/vmstat.pid): failed to open stream: No such file or directory"
 *  ["file"]=>
 *      string(72) "/home/mint/workspace/inframe/inframe/vendor/workerman/workerman/Worker.php"
 *  ["line"]=>
 *      int(646)
 *  ["class"]=>
 *      string(7) "Error 2"
 * }
 *  // Get master process PID.
 *  $master_pid = @file_get_contents(self::$pidFile);
 *  改为
 *  $master_pid = is_file(self::$pidFile) ? file_get_contents(self::$pidFile) : 0;
 *
 *
 * ~/inframe/vendor/workerman/workerman/Protocols/Http.php
 * @\session_start();
 * 改为
 * headers_sent() or session_start();
 *
 *
 * @package inframe\library
 */
abstract class Service
{
    protected $memory_limit = '1024M';

    protected $port = 0;

    public function __construct($port)
    {
        $this->port = $port;
        ini_set('memory_limit', $this->memory_limit);
        spl_autoload_register(function ($classname) {
            $class_path = trim(str_replace('\\', '/', $classname), '/ ');
            # 检查是否是workerman
            if (strpos($classname, 'Workerman\\') === 0) {
                $class_file = __DIR__ . '/../vendor/workerman/workerman/' . substr($class_path, 10) . '.php';
            } elseif (strpos($classname, 'PHPSocketIO\\') === 0) {
                $class_file = __DIR__ . '/../vendor/workerman/phpsocket.io/src/' . substr($class_path, 12) . '.php';
            } elseif (strpos($classname, 'GatewayWorker\\') === 0) {
                $class_file = __DIR__ . '/../vendor/workerman/gateway-worker/src/' . substr($class_path, 14) . '.php';
            } else {
                return false;
            }

            if (is_file($class_file)) {
                require $class_file;
                return true;
            }
            return false;
        });
        Worker::$pidFile = IN_PATH_RUNTIME . str_replace(['\\', '/'], '_', self::class) . $port . '.pid';
    }

    /**
     * 运行所有服务
     * @return void
     */
    public function start()
    {
        Worker::runAll();
    }

    /**
     * 后台执行命令
     * @param string $command
     * @return void
     */
    public static function exec($command)
    {
        if (IN_IS_WIN) {
            $pipe = popen("start /B {$command}", 'r');
            pclose($pipe);
        } else {
            exec("{$command} > /dev/null &");
        }
    }
}